/**
 * 获取公众号用户发送的数据
 */

/**
 * npm i xml2js
 * 将xml格式转换为js对象
 */
const {parseString} = require('xml2js');//xml2js里面的parseString将格式转换为js

//参数变量
let ToUserName = "";
let FromUserName = "";
let CreateTime = "";
let MsgType = "";
let Content = "";
let MsgId = "";

//获取接收的数据
async function getUserSendPostAsync(req){
    return new Promise((resolve,reject)=>{
        try{
            let data = "";
            req.on('data',chunk=>data += chunk);
            req.on('end',()=>{
                resolve(data);
            });
        }catch(err){
            reject(err);
        }
    })
}

//将xml文件转换为js对象的方法
async function xmlToJsFunc(dataMsg){
    return new Promise((resolve,reject)=>{
        parseString(dataMsg,async(err,data)=>{
            if(!err){
                dataMsg = await data.xml;
                ToUserName = await dataMsg.ToUserName[0];
                FromUserName = await dataMsg.FromUserName[0];
                CreateTime = await dataMsg.CreateTime[0];
                MsgType = await dataMsg.MsgType[0];
                Content = await dataMsg.Content[0];
                MsgId = await dataMsg.MsgId[0];
                resolve(dataMsg);
            }else {
                reject(err);
            }
        })
    })
}

//将发送过来的数据装换成js对象
async function xmlToJsOfForm(dataMsg){
    return new Promise((resolve,reject)=>{
        parseString(dataMsg,async(err,data)=>{
            if(!err){
                dataMsg = await data.xml;
                ToUserName = await dataMsg.ToUserName[0];
                FromUserName = await dataMsg.FromUserName[0];
                CreateTime = await dataMsg.CreateTime[0];
                MsgType = await dataMsg.MsgType[0];
                Content = await dataMsg.Content[0];
                resolve(dataMsg);
            }else {
                reject(err);
            }
        })
    })
}


module.exports = {
    getUserSendPostAsync,//获取接收的数据
    xmlToJsFunc,//将xml文件转为js对象
    ToUserName,FromUserName,CreateTime,MsgType,Content,MsgId,//变量参数,有发送接收方信息和发送消息内容
    xmlToJsOfForm,//将form表单的xml数据转换成js对象
}